import service from '@/utils/request'
import {getDataQuery} from '@/api/dataSource'

const path = '/WorkBook'

/**
 * 分页获取图表列表
 * @param data
 * @returns {*}
 */
export function getList(data) {
  return service.get(path + "/getList", {
    params: data
  })
}

/**
 * 获取图表对象
 * @param workBookId
 * @returns {Promise<AxiosResponse<any>>}
 */
export function getWorkBook(workBookId) {
  return service.get(path + "/getWorkBook", {
    params: {
      id: workBookId
    }
  })
}

/**
 * 转换成Obj
 * @param workBook
 * @returns {{colorMark}|*}
 */
export function parseToObj(workBook) {
  if (typeof workBook.chartConfig === 'string') {
    workBook.chartConfig = JSON.parse(workBook.chartConfig)
  }
  if (typeof workBook.rows === 'string') {
    workBook.rows = JSON.parse(workBook.rows)
  }
  if (typeof workBook.columns === 'string') {
    workBook.columns = JSON.parse(workBook.columns)
  }
  if (typeof workBook.filters === 'string') {
    workBook.filters = JSON.parse(workBook.filters)
  }
  if (typeof workBook.subDimension === 'string') {
    workBook.subDimension = JSON.parse(workBook.subDimension)
  }
  if (typeof workBook.urlParams === 'string') {
    workBook.urlParams = JSON.parse(workBook.urlParams)
  }
  if (typeof workBook.limit === 'string') {
    workBook.limit = JSON.parse(workBook.limit)
  }
  if (typeof workBook.rankMark === 'string') {
    workBook.rankMark = JSON.parse(workBook.rankMark)
  }
  return workBook
}


/**
 * 加载数据
 * @param WorkbookModel 图表对象
 * @param dataSource 数据源对象
 * @param showLoading 是否显示loading
 * @param isQueue 是否队列执行
 */
export function loadData(WorkbookModel, dataSource, showLoading , isQueue) {
  return new Promise((resolve, reject) => {
    //查询的字段信息
    const fields = WorkbookModel.rows.concat(WorkbookModel.columns);

    //处理分析的全局筛选
    if (WorkbookModel.filters && WorkbookModel.globalFilter) {
      resolverFilter(WorkbookModel.filters, WorkbookModel.globalFilter)
    }
    //处理外链参数
    const urlParams = WorkbookModel.urlParams
    urlParams.forEach(param => {
      let value = getUrlKey(param.name, window.location.href);
      if (value) {
        if (value.includes(",")) {
          value = value.split(",");
        } else {
          value = [value];
        }
        let filter = filters.find(d => d.field.systemName == param.field.systemName && d.field.tableName == param.field.tableName);
        if (filter) {
          filter.filterMode = 0;
          filter.filterItems = value;
        } else {
          filter = {
            field: param.field,
            filterMode: 0,
            filterItems: value
          };
        }
        filters.push(filter);
      }
    });

    //处理二级维度
    const subDimension = WorkbookModel.subDimension
    if (subDimension && subDimension.length) {
      fields.push(subDimension[0]);
    }

    const limit = WorkbookModel.limit
    const _currentDataSource = dataSource

    let workBookId = WorkbookModel?WorkbookModel.id:'';

    let dataSourceId = dataSource?dataSource.id:'';

    //构建查询参数对象
    const request = {
      repositorySourceId: _currentDataSource.repositoryId,
      dataProviderType: _currentDataSource.dataProviderType,
      fields: fields,
      filters: WorkbookModel.filters,
      limit: limit,
      queryType: _currentDataSource.queryType,
      sql: _currentDataSource.syntax,
      isYoy: WorkbookModel.isYoy,
      yoyType: WorkbookModel.yoyType,
      noCache: WorkbookModel.autoUpdate > 0,
      Comments: `请求图表【${WorkbookModel.name}】数据`,
      workBookId: workBookId,
      dataSourceId: dataSourceId,
      showLoading: showLoading
    }
    if (!WorkbookModel.id || !WorkbookModel.name) {
      request.Comments = "新建的图表请求数据";
    }

    let directExec = true
    if (isQueue) {
      directExec = false
    }

    try {
      getDataQuery(request, data => {
        console.log("数据源查询结果:");
        console.log(data);
        resolve(data);
      }, directExec)
    } catch (e) {
      console.error(e)
      reject(e)
    }
  })
}
;

/**
 * 将全局筛选器覆盖到图表对应的筛选器上
 * @param filters
 * @param globalFilter
 */
const resolverFilter = (filters, globalFilter) => {
  filters.forEach(d => {
    const mf = globalFilter[d.mark];
    if (mf !== undefined && mf.enable) {
      switch (d.mark) {
        case "date":
          if (mf.date_range) {
            d.beginDate = mf.date_range[0]
            d.endDate = mf.date_range[1]
          } else {
            d.beginDate = null
            d.endDate = null
          }
          d.filterMode = 4;
          break;
      }
    }
  });
}

/**
 * 删除指定的图表
 * @param workBookId
 * @returns {Promise<AxiosResponse<any>>}
 */
export function delWorkBook(workBookId) {
  return service.get(path + "/delWorkBook", {
    params: {
      id: workBookId
    }
  })
}

/**
 * 保存图表
 * @param data
 * @returns {Promise<AxiosResponse<any>>}
 */
export function saveWorkBook(data) {
  let WorkbookModel = Object.assign({}, data);
  WorkbookModel.filters = JSON.stringify(WorkbookModel.filters);
  WorkbookModel.rows = JSON.stringify(WorkbookModel.rows);
  WorkbookModel.columns = JSON.stringify(WorkbookModel.columns);
  WorkbookModel.subDimension = JSON.stringify(WorkbookModel.subDimension);
  WorkbookModel.rankMark = JSON.stringify(WorkbookModel.rankMark);
  WorkbookModel.urlParams = JSON.stringify(WorkbookModel.urlParams);
  WorkbookModel.limit = JSON.stringify(WorkbookModel.limit);
  WorkbookModel.chartConfig = JSON.stringify(WorkbookModel.chartConfig);
  if (WorkbookModel.dataMarking && typeof WorkbookModel.dataMarking != "string") {
    WorkbookModel.dataMarking = JSON.stringify(WorkbookModel.dataMarking);
  }
  if (WorkbookModel.havingFilters && typeof WorkbookModel.havingFilters != "string") {
    WorkbookModel.havingFilters = JSON.stringify(WorkbookModel.havingFilters);
  }
  return service.post(path + "/saveWorkBook", WorkbookModel)
}

function getUrlKey(name, url) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null
}

/**
 * 将字符串转换成对象
 * @param WorkbookModel
 */
export function resolveWorkBookModel(WorkbookModel) {
  WorkbookModel.rows = JSON.parse(WorkbookModel.rows);
  WorkbookModel.columns = JSON.parse(WorkbookModel.columns);
  WorkbookModel.filters = JSON.parse(WorkbookModel.filters);
  WorkbookModel.colorMark = JSON.parse(WorkbookModel.colorMark);
  if (WorkbookModel.tableTheme !== undefined) {
    WorkbookModel.tableTheme = JSON.parse(WorkbookModel.tableTheme);
  } else {
    WorkbookModel.tableTheme = {};
  }
  if (WorkbookModel.rankMark !== undefined) {
    WorkbookModel.rankMark = JSON.parse(WorkbookModel.rankMark);
  } else {
    WorkbookModel.rankMark = [];
  }
  if (WorkbookModel.urlParams) {
    WorkbookModel.urlParams = JSON.parse(WorkbookModel.urlParams);
    WorkbookModel.urlParams.forEach(function (param) {
      var value = getUrlKey(param.name, window.location.href);
      if (value) {
        if (value.includes(",")) {
          value = value.split(",");
        } else {
          value = [value];
        }
        WorkbookModel.filters.push({
          field: param.field,
          filterMode: 0,
          filterItems: value
        });
      }
    });
  }
  if (WorkbookModel.labelOption) {
    WorkbookModel.labelOption = JSON.parse(WorkbookModel.labelOption);
  }
  if (WorkbookModel.limit) {
    WorkbookModel.limit = JSON.parse(WorkbookModel.limit);
  }
  if (WorkbookModel.chartConfig) {
    WorkbookModel.chartConfig = JSON.parse(WorkbookModel.chartConfig);
  }
  if (typeof WorkbookModel.produceParameters === "string") {
    WorkbookModel.produceParameters = JSON.parse(WorkbookModel.produceParameters);
  }
  return WorkbookModel
}

